<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { postMsgTemplate } from '#/api/plugin/wechat';

const [Form, formApi] = useVbenForm({
  layout: 'vertical',
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      dependencies: {
        disabled: true,
        // 随意一个字段改变时，都会触发
        triggerFields: ['title'],
      },
      componentProps: {
        placeholder: '请输入',
      },
      fieldName: 'title',
      label: '模板名称',
    },
    {
      component: 'Textarea',
      dependencies: {
        disabled: true,
        // 随意一个字段改变时，都会触发
        triggerFields: ['content'],
      },
      componentProps: {
        placeholder: '请输入',
        autoSize: true,
      },
      fieldName: 'content',
      label: '模板内容',
    },
    {
      component: 'Textarea',
      fieldName: 'fields',
      label: '模板参数',
    },
  ],
  showDefaultActions: false,
});
const gridOptions: VxeGridProps<any> = {
  columns: [
    { field: 'key', title: '参数' },
    {
      editRender: { name: 'input' },
      field: 'value',
      title: '参数设置',
      align: 'left',
    },
  ],
  pagerConfig: {
    enabled: false,
  },
  editConfig: {
    mode: 'cell',
    trigger: 'click',
  },
  showOverflow: true,
};

const [Grid, GridApi] = useVbenVxeGrid({ gridOptions });
const parseTemplate = (template: string) => {
  const regex = /\{\{(.*?)\}\}/g;
  const result: Array<{ key: string; value: string }> = [];
  let match;
  while (true) {
    match = regex.exec(template);
    if (match === null) break;
    const key = match[1];
    if (key) {
      result.push({ value: '', key: key.replace(/\.DATA$/, '') });
    }
  }
  return result;
};
const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    formModalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: any = formModalApi.getData();
      if (values) {
        const fields = values.fields ?? parseTemplate(values.content);
        formApi.setValues(values);
        GridApi.setGridOptions({ data: fields });
      }
    }
  },
});

async function onSubmit(values: any) {
  function showMsg(msg: string) {
    message.success(msg);

    formModalApi.setData({ isUpdata: true });
    formModalApi.close();
  }
  let fields = values.fields;
  if (GridApi.grid.data) {
    fields = GridApi?.grid?.data.map((item: any) => {
      return {
        key: item.key,
        value: item.value,
      };
    });
  }
  values.fields = fields;
  const { msg } = await postMsgTemplate(values);
  showMsg(msg);
}
</script>
<template>
  <Modal class="w-3/5">
    <Form>
      <template #fields>
        <Grid class="w-full" />
      </template>
    </Form>
  </Modal>
</template>

<style lang="scss" scoped></style>
